<template>
	<view class='m-video' @click="controlstoggle">
		<!-- #ifdef APP-PLUS -->
		<!-- 	<mXgPlayer v-if="storyUrl" :ref="'mXgPlayer'+storyId" :storyId="storyId" :autoplay="autoplay"
			:storyUrl="storyUrl" @canplay="onLoadedmetadata" @timeupdate="onTimeUpdate" @play="onPlay" @pause="onPause"
			@ended="onEnded" @error="videoErrorCallback" @seeked="seekcomplete" @longpress.stop="handleLongPress"
			@touchend.stop="handleTouchEnd">
			<template v-slot:vidoeContent>
				<slot name="videoCover"></slot>
			</template>

		</mXgPlayer> -->
		<!-- #endif -->
		<!-- #ifndef APP-PLUS -->
		<video :id="storyId" v-if="storyUrl" :codec="codec" :loop="false" :muted="nowMuted" :autoplay="autoplay"
			:play-strategy="2" :http-cache="false" :show-play-btn="false" :enable-play-gesture="enablePlayGesture"
			play-btn-position="center" :controls="controls" :show-fullscreen-btn="false" :show-progress="false"
			:page-gesture="false" :vslide-gesture="false" :vslide-gesture-in-fullscreen="false" :show-loading="false"
			:enable-progress-gesture="false" :src="storyUrl" :mobilenet-hint-type="0" object-fit="cover"
			:style="{ width: width,height:height }" @loadedmetadata="onLoadedmetadata" @timeupdate="onTimeUpdate"
			@play="onPlay" @pause="onPause" @ended="onEnded" @error="videoErrorCallback" @seekcomplete="seekcomplete"
			@longpress.stop="handleLongPress" @touchend.stop="handleTouchEnd">
			<slot name="videoCover">
			</slot>
		</video>
		<!-- #endif -->
		<!-- :style="{'background-image': `url(${coverImgUrl})` }" -->
		<view class="cover-box" v-if="!storyUrl" @longpress="handleLongPress" @touchend="handleTouchEnd">
			<view class="cover-actions">
				<slot name="videoCover">

				</slot>
			</view>
			<image v-show="!goNextStoryFlag" class="cover-bg-image" :src="coverImgUrl" mode="aspectFill"></image>


		</view>




	</view>
</template>

<script>
	import {
		mapState,
	} from "vuex"
	// import mXgPlayer from "@/components/m-xg-player/index.vue"
	export default {
		components: {
			// mXgPlayer
		},
		props: {
			width: {
				type: String,
				default: "100vw"
			},
			height: {
				type: String,
				default: "100vh"
			},
			autoplay: {
				type: Boolean,
				default: false
			},
			true: {
				type: Boolean,
				default: false
			},
			enableProgressGesture: {
				type: Boolean,
				default: false
			},
			enablePlayGesture: {
				type: Boolean,
				default: false
			},
			controls: {
				type: Boolean,
				default: false
			},
			storyUrl: {
				type: String,
				default: ''
			},
			coverImgUrl: {
				type: String,
				default: ''
			},
			storyType: {
				type: String,
				default: ''
			},
			checkoutEvent: {
				type: [String]
			},
			storyId: {
				type: [Number, String],
				default: Math.random()
			},
			// 是否应用于首页
			inHome: {
				type: Boolean,
				default: false,
			},
			// 是否包含多个剧情片段
			isMultiVideo: {
				type: Boolean,
				default: false,
			},
			// 剧情片段配置
			sectionsConfig: {
				type: Array,
				default: [],
			},
			// 倒数循环
			selfLoop: {
				type: Boolean,
				default: false
			},
			canClick: {
				type: Boolean,
				default: false
			},
			// 倒数循环秒数  0 ：不循环    2：循环倒数2秒
			loopSec: {
				type: Number,
				default: 0
			},
			goNextStoryFlag: {
				type: Boolean,
				default: false
			},
			useType: {
				type: String,
				default: "default", // defautl 普通使用  alone 单独使用
			}

		},

		computed: {
			...mapState(['curStoryId', 'curStoryType']),
			checkoutEventTimePoints() {
				let result = []
				if (this.checkoutEvent) {
					result = this.checkoutEvent.split(';').map(item => {
						return item = (Number(item) / 1000)
					})
				}
				return result
			},
			nowMuted() {
				if (this.curStoryId != this.storyId && this.useType !== 'alone') {
					return true
				} else {
					return false
				}
			},
		},
		watch: {
			statusObj: {
				handler(newV, oldV) {
					let {
						playStatus,
						stopStatus
					} = newV

					let flag = false

					// // #ifdef MP-TOUTIAO
					// flag = playStatus === stopStatus
					// // #endif

					// // #ifndef MP-TOUTIAO
					// flag = (playStatus === stopStatus) && (this.storyId == this.curStoryId)
					// // #endif
					flag = (playStatus === stopStatus) && (this.storyId == this.curStoryId)

					// if (flag) {
					// 	console.log("监听到矛盾");
					// 	this.videoContext.play()
					// 	this.playChangeStatus()
					// }
				},
				deep: true
			},

		},
		data() {
			return {
				duration: 0,
				canPlay: false,
				videoContext: null,
				isPlaying: true,
				codec: "software",
				onEndedEvent: false, //是否触发过
				videoLoading: true, //是否触发过
				statusObj: {
					playStatus: false,
					stopStatus: true,
				},
				playAgain: false,

			}
		},
		onLoad(option) {

		},

		onReady() {

		},
		created() {},
		mounted() {
			if (!this.storyUrl) {
				this.canPlay = true
			}
			// #ifdef APP-PLUS
			// this.videoContext = this.$refs['mXgPlayer' + this.storyId]
			// #endif

			// #ifndef APP-PLUS
			this.videoContext = uni.createVideoContext(this.storyId, this)
			// #endif


		},
		beforeDestroy() {

		},
		methods: {
			// 跳转视频进度
			seekEvent(seekEventTime) {
				this.videoContext.seek(seekEventTime)
			},
			stopChangeStatus() {
				// this.statusObj.playStatus = false
				// this.statusObj.stopStatus =  true
				this.statusObj = {
					playStatus: false,
					stopStatus: true
				}
			},
			playChangeStatus() {
				// this.statusObj.playStatus = true
				// this.statusObj.stopStatus =  false
				this.statusObj = {
					playStatus: true,
					stopStatus: false
				}
			},
			seekcomplete(e) {
				// console.log(`剧情【${this.storyId}】 onSeeking-------------`, e.detail)
				// #ifdef MP-TOUTIAO
				// if (this.curStoryId && (this.curStoryId === this.storyId)) {
				// 	console.log(`剧情【${this.storyId}】 onSeeking中播放-------------`)
				// 	setTimeout(() => {
				// 		this.videoContext.play();
				// 	}, 100);
				// }
				// #endif

			},
			getDuration() {
				return this.duration > 0
			},
			onLoadedmetadata(e) {
				// this.initTime=new Date().getTime()
				// console.log(`剧情【${this.storyId}】资源加载完毕 onLoadedmetadata-------------`)
				if (this.videoLoading) {
					this.videoContext.play();
					this.playChangeStatus()
				}

				if (!this.canPlay) {
					setTimeout(() => {
						this.canPlay = true
						if (this.useType == 'alone') {
							return
						}
						if (!this.inHome && this.storyId != this.curStoryId && this.curStoryType != 'agentChat') {
							this.videoContext.seek(0)
							this.videoContext.pause()
							this.stopChangeStatus()
						}

					}, 1000)
				}

				this.$emit('onLoadedmetadata', e)

			},
			onTimeUpdate(e) {
				this.$emit('onTimeUpdate', e)
				let currentTime = e.detail.currentTime
				let duration = e.detail.duration
				// console.log(`【${this.storyId}】正则播放`, currentTime);
				// console.log(currentTime, this.checkoutEventTimePoints, 'onTimeUpdate---------')
				if (!this.duration) {
					this.duration = duration
				}

				// 在此组件只需要抛出相关通用事件（是否在循环过程触发跳转，由上级业务组件自行判断

				if (this.selfLoop) {
					if (this.loopSec > 0 && (duration - currentTime) <=
						this.loopSec) {
						// 循环倒数几秒时，且在循环内，则根据跳出点进行发送

						this.checkoutEventTimePoints.forEach(point => {
							if ((currentTime > point - 0.1) && (currentTime < point + 0.1)) {
								this.$emit('handleCheckoutEvent')
							}
						})

					} else if (this.loopSec < 0) {
						// 循环整个视频时，且在循环内，则根据跳出点进行发送
						this.checkoutEventTimePoints.forEach(point => {
							if ((currentTime > point - 0.1) && (currentTime < point + 0.1)) {
								this.$emit('handleCheckoutEvent')
							}
						})
					}
				}
				// 分段剧情配置检测
				if (this.isMultiVideo) {
					if (this.storyId == this.curStoryId) {
						this.sectionsConfig.forEach(section => {
							if (section.sectionStartTime >= 0 && section.sectionEndTime != -1 && (currentTime >= (
									section.sectionEndTime - 0.250)) &&
								(currentTime <= (section.sectionEndTime + 0.250))) {
								// console.log(currentTime, section, section.sectionName,
								// 	'处于分段剧情结束范围点内----onTimeUpdate---')
								this.dealSectionEvent(section)
							}
						})
					}

				}



			},
			dealSectionEvent(section) {
				switch (section.sectionEndEvent) {
					case 'continue':
						// 继续播放,什么也不做
						break;
					case 'pause':
						// 暂停
						this.pauseVideo()
						break;
					case 'loop':
						// 循环
						this.videoContext.seek(section.sectionStartTime)

						break;
					case 'seek':
						// 跳转秒数
						this.videoContext.seek(section.sectionSeekEventTime)
						break;
					case 'startGame':
						// 开始游戏(应用于首页时,例如<少妇>项目)
						this.$emit('startGame')
						break;

				}
			},
			onPlay(e) {
				this.playChangeStatus()
				// if (this.autoplay && !this.playAgain) {
				// 	// 初始化进入时，触发矛盾播放一次
				// 	this.videoContext.pause()
				// 	this.playAgain = true
				// }
				// console.log(
				// 	`剧情【${this.storyId}】触发播放 onPlay--------------是否需要加载${this.videoLoading}自动播放${this.autoplay}第二次播${this.playAgain}`
				// )
				this.$emit('onPlay', e)
				if (this.videoLoading) {
					this.videoLoading = false //视频加载完毕
					try {
						if (!this.autoplay) {
							this.videoContext.seek(0)
							// #ifdef MP-WEIXIN
							this.videoContext.pause()
							this.stopChangeStatus()
							// #endif

							// #ifdef MP-TOUTIAO
							if (this.curStoryId && (this.curStoryId != this.storyId)) {
								this.videoContext.pause()
								this.stopChangeStatus()
								console.log(
									`当前播放剧情【${this.curStoryId}】，当前要暂停的剧情【${this.storyId}】 onPlay----------this.videoLoading`
								)
							}
							// #endif

						}
					} catch (e) {
						//TODO handle the exception
					}

					setTimeout(() => {
						// console.log("来吧", this.storyId);
						this.canPlay = true //视频加载完毕
						// let initTime=new Date().getTime()
						// console.log(this.storyId,initTime-this.initTime, 'onPlay---------视频加载完毕')
					}, 0);

				} else {
					if (this.useType == 'alone') {
						return
					}


					if (!this.inHome && (this.curStoryId != this.storyId) && this.curStoryType != 'agentChat') {
						// console.log(`【${this.storyId}】这是啥`);
						this.videoContext.pause()
						this.stopChangeStatus()
					}
				}

			},
			onPause(e) {
				console.log("暂停监听")
				let time = new Date().getTime()
				let playStatus = this.statusObj.playStatus
				this.statusObj = {
					stopStatus: true,
					playStatus: playStatus
				}

				this.$emit('onPause', e)
			},
			onEnded(e) {
				this.stopChangeStatus()
				if (!this.onEndedEvent) {
					this.onEndedEvent = true
				}
				if (this.selfLoop) {
					this.rePlaySecVideo()
				}
				// 分段剧情配置检测
				if (this.isMultiVideo) {
					this.sectionsConfig.forEach(section => {
						if (section.sectionStartTime >= 0 && section.sectionEndTime === -1) {
							console.log(section, '处于分段剧情结束范围点内----onEnded---')
							this.dealSectionEvent(section)
						}
					})
				}
				this.$emit('onEnded')
			},
			videoErrorCallback(e) {
				console.log('videoErrorCallback播放错误---')
				this.$emit('videoErrorCallback', e)

				if (this.selfLoop && this.loopSec < 0) {
					this.videoContext.seek(0);
					this.playVideo()
				}
			},
			handleLongPress() {
				console.log("长按");
				this.$emit('handleLongPress')
			},
			handleTouchEnd(e) {
				this.$emit('handleTouchEnd', e)
			},
			controlstoggle() {
				this.$emit("videoClick")
				if (this.canClick) {
					this.isPlaying = !this.isPlaying
					if (this.isPlaying) {
						this.playVideo()
					} else {
						this.pauseVideo()
					}
					this.$emit('controlstoggle', !this.isPlaying)
				} else {
					this.$emit('nomalClick')
				}
			},
			playbackRate(rate) {
				console.log("调用快进", rate);

				this.videoContext.playbackRate(rate);
			},
			playVideo() {
				if (this.videoContext) {
					console.log("进入触发播放");
					this.videoContext.play();
				}
				this.playChangeStatus()
			},
			pauseVideo() {
				this.videoContext.pause();
				this.stopChangeStatus()
			},
			stopVideo(callback, destory = false) {
				if (this.videoContext) {
					this.resetState()
					this.videoContext.seek(0) //需要手动归零，否则返回会先触发某些条件函数
					this.videoContext.pause();
					this.stopChangeStatus()
					if (destory) {
						this.canPlay = false
					}
					callback(true)
				}
			},
			resetState() {
				this.onEndedEvent = false
			},
			async rePlayVideo(callback, seekTime = 0) {
				this.$nextTick(() => {
					this.videoContext.seek(seekTime)
					this.videoContext.play()
					this.playChangeStatus()
					console.log(`剧情【${this.storyId}】调用播放`, seekTime);
					if (seekTime > 0) {
						setTimeout(() => {
							callback(true)
						}, 500);
					} else {
						callback(true)
					}

				})
			},
			/**
			 * @desc 重复播放倒数n秒
			 */
			async rePlaySecVideo() {
				console.log(`[【调用重复播放${this.storyId}】`, );
				if (this.duration) {
					if (this.loopSec > 0) {
						await this.videoContext.seek(this.duration - this.loopSec < 0 ? 0 : this.duration -
							this.loopSec);
					} else if (this.loopSec < 0) {
						await this.videoContext.seek(0);
					}
				}
				this.videoContext.play();
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import './index.scss';

	.cover-box {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100vw;
		height: 100vh;
		z-index: 9;
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center center;
		z-index: 9999999999999999;

		.cover-bg-image {
			position: absolute;
			left: 0rpx;
			top: 0rpx;
			width: 100vw;
			height: 100vh;
			z-index: 1;
		}

		.cover-actions {
			position: absolute;
			left: 0rpx;
			top: 0rpx;
			width: 100vw;
			height: 100vh;
			z-index: 999999999999999999999;
		}


	}

	::v-deep {
		#xgplayer-error {
			.xgplayer-error-refresh {
				color: red;
			}
		}
	}
</style>